//
//  ComposeViewController.swift
//  SinaWeibo23
//
//  Created by apple on 16/2/25.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    
    
    //自定义的表情键盘
    private lazy var keyBoardView: EmoticonKeyBoardView = EmoticonKeyBoardView {[weak self] (em) -> () in
        //[weak self]  在闭包中 使用是self 都是弱引用自己
        
        self?.textView.insertEmoticonImage(em)
    }
    
    
    //MARK: 关闭页面
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func selectEmoticon() {
        printLog(__FUNCTION__)
        //系统键盘还是第一响应者
        //取消键盘的第一响应者
        //如果inputView = nil 当前显示的就是系统键盘
        printLog(textView.inputView)
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? keyBoardView : nil
        //将textView设置成为第一响应者
        textView.becomeFirstResponder()
    }
    
    
    @objc private func selectPicture() {
        //更新约束
        
        pictureSelector.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK: 发布微博
    @objc private func send() {
        printLog(__FUNCTION__)
        
        //发布文本微博
        var urlString = "2/statuses/update.json"
        guard let token = AccountViewModel.sharedAccountViewModel.access_token else {
            SVProgressHUD.showErrorWithStatus("请登录")
            return
        }
        let parameters = ["access_token": token,"status": textView.fullText()]
        printLog(textView.text)
        if pictureSelector.imageList.count > 0 {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //需要调用发布图片微博的接口
            //如何上传多张图片
            let imageData = UIImagePNGRepresentation(self.pictureSelector.imageList.first!)!
            HTTPClient.sharedClient.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                
                //新浪微博的接口只允许上传单张图片  多张图片的接口是高级权限
                //将需要上传的文件转换为二进制的数据 拼接到 formData 中
                //1.data: 需要上传的文件的二进制数据
                //2.name: 服务器的接收字段名
                //3.fileName  服务器存储的文件名称  微博的服务器 会自己重写命名
                //4.mimeType: 文件格式  application/octet-stream: 八进制流 任意文件类型都可以
                //image/jpeg	 图片的文件格式
                
                var index = 0
                for image in self.pictureSelector.imageList {
                    let data = UIImagePNGRepresentation(image)!
                    formData.appendPartWithFileData(data, name: "pic", fileName: "fileName\(index)", mimeType: "image/jpeg")
                    index++
                }
//                formData.appendPartWithFileData(imageData, name: "pic", fileName: "ooxxxxxx", mimeType: "application/octet-stream")
                }, progress: nil, success: { (_, result) -> Void in
                    printLog(result)
                    SVProgressHUD.showSuccessWithStatus("发布微博成功")
                    self.close()
                }, failure: { (_, error) -> Void in
                    printLog(error)
            })
        } else {
           
            
            HTTPClient.sharedClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                if error != nil {
                    //发布微博失败
                    SVProgressHUD.showErrorWithStatus("发布微博失败,请检查网络")
                    return
                }
                
                printLog(dict!)
                
                //dismiss
                self.close()
            }
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        setTextView()
        setBottomToolBar()
        setPictureSelector()
        //注册通知
        registerNotification()
        
    }
    
    
    @objc private func keyBoardWillChange(n: NSNotification) {
        printLog(n)
        //在动画闭包中 修改底部的工具条的位置 更新底部约束
        //1.获取动画运行的时间
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //2.键盘结束的frame CGRect 是结构体 结构体需要转换成 NSValue对象才能够添加到 字典中
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //3.动画曲线
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        let height = -ScreenHeight + rect.origin.y
        //在动画闭包中更新约束
        UIView.animateWithDuration(duration) { () -> Void in
            //在动画闭包中设置动画曲线
            //通过原始值 获取枚举类型的对象]
            //枚举类型为 7 标示忽略时间
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            //1.更新约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                //值是负的
                make.bottom.equalTo(height)
            })
            //2.强制刷新页面
            self.view.layoutIfNeeded()
        }
        
    }
    
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //懒加载 textView视图
    private lazy var textView: EmoticonTextView = {
        let tv = EmoticonTextView()

//        tv.text = "输入新鲜事..."
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.lightGrayColor()
        tv.backgroundColor = UIColor.greenColor()
        tv.alwaysBounceVertical = true
        //keyboardDismissMode  这个属性起作用的前提 是滚动视图可以滚动
        tv.keyboardDismissMode = .OnDrag
        
        //设置textView的代理
        tv.delegate = self
        return tv
    }()
    
    
    //底部工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var placeHolder: UILabel = UILabel(text: "输入新鲜事...", fontSize: 18, textColor: UIColor(white: 0.7, alpha: 1))
    
    //图片选择器的控制器
    private lazy var pictureSelector: PictureSelectorViewController = PictureSelectorViewController()

}


//MARK: UI设置相关的分类
extension ComposeViewController {
    
    
    private func setPictureSelector() {
        //1.添加视图控制器  视图树错误的警告  Presenting view controllers on detached view controllers is discouraged
        /*
        If the child controller has a different parent controller, it will first be removed from its current parent
        by calling removeFromParentViewController. If this method is overridden then the super implementation must
        be called.
        */
        self.addChildViewController(pictureSelector)
        
        //2.添加视图控制器的视图
        self.view.addSubview(pictureSelector.view)
        
        //3.将toolbar 移动到最顶层
        self.view.bringSubviewToFront(toolBar)
        //4.设置约束
        pictureSelector.view.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.bottom.equalTo(self.view.snp_bottom)
            make.height.equalTo(0)
        }
        
    }
    
    private func setBottomToolBar() {
        //天机工具条视图
        view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            //高度  toolbar 有默认高度 默认是44
            //            make.height.equalTo(44)
        }
        
        //设置toolbar 内部的按钮
        var items = [UIBarButtonItem]()
        //配置类型字典
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        for item in itemSettings {
            //实例化UIBarButtonItem对象  默认的渲染色 是蓝色 并且不能够设置高亮状态的图片
            let imageName = item["imageName"]
            let btn = UIButton(backImageName: nil, imageName: imageName!)
            if let actionName = item["actionName"] {
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            let barItem = UIBarButtonItem(customView: btn)
            //将对象添加到数组中
            items.append(barItem)
            
            //添加弹簧的item
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        //移除最后一个
        items.removeLast()
        
        //设置工具条的按钮数组对象
        toolBar.items = items
    }
    
    
    
    private func setTextView() {
        //添加 子视图
        view.addSubview(textView)
        //设置约束 约束完一个控件就立即查看布局效果
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_top)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.height.equalTo(ScreenHeight / 3)
        }
        
        //添加占位文本
        textView.addSubview(placeHolder)
        //设置占位文本的约束
        placeHolder.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    
    //设置导航条
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        
        //初始的时候 设置发布按钮不能交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        
        //自定义到航条 titleView
        let weiboTitle = UILabel(text: "发布微博", fontSize: 18, textColor: UIColor.darkGrayColor())
        let nameLabel = UILabel(text: AccountViewModel.sharedAccountViewModel.userName ?? "", fontSize: 13, textColor: UIColor.lightGrayColor())
        // navigationItem.titleView 默认值是nil 要实现添加的操作 需要赋值
        printLog(navigationItem.titleView)
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        navigationItem.titleView?.addSubview(weiboTitle)
        navigationItem.titleView?.addSubview(nameLabel)
        //设置约束
        weiboTitle.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        
    }
}


extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //如果用户输入了文本 点亮按钮,隐藏占位文本
        //用户没有输入任何文本  恢复到默认状态
        placeHolder.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
